const path = require('path')
const fs = require('fs')
const chalk = require('chalk')
const { promisify } = require('util')
const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)
const regMap = require('./regMap')
const inquirer = require('inquirer')
const glob = require('glob')
const { validate, leftCount, imgMin } = require('./tinyfy')
const { resolve } = require('path')
const { rejects } = require('assert')

class ImgMin {
  constructor(conf) {
    if (!conf.imgMinPath) {
      conf.imgMinPath = process.cwd() //如果用户没输入路径的话,就直接用根目录
    }
    this.conf = conf
    // console.log('最后的地址为',this.conf.imgMinPath);
    this.imgs = 0
    this.fileNum = 0
  }

  //判断是否是文件夹
  async isDir(filePath) {
    try {
      const stats = await stat(filePath)
      if (stats.isDirectory()) {
        return true
      }
      return false
    } catch (error) {
      return false
    }
  }
  //查找图片资源
  async findImg(filePath) {
    try {
      const isDirectory = await this.isDir(filePath)
      if (!isDirectory) {
        return
      }
      const files = await readdir(filePath)
      // console.log('files',files);
      for (let file of files) {
        // 这里不能用forEach，只能用for循环
        // await this.getImg(file);
        const fullPath = path.join(filePath, file)
        // console.log('fullPath',fullPath);
        this.getImg(fullPath)
      }
    } catch (error) {
      console.log(error)
    }
  }

  async getImg(file) {
    const stats = await stat(file)
    // 如果是文件夹，则递归调用findImg
    //判断当前文件是否一个目录
    if (stats.isDirectory()) {
      this.findImg(file)
    } else if (stats.isFile()) {
      //判断当前文件是否一个普通文件
      if (regMap.isTinyPic.test(file)) {
        this.imgs++
        const left = leftCount()
        // 剩余数判断，解决同步时剩余数不足导致的全部图片压缩失败问题
        if (this.imgs > left || left < 0) {
          console.log(chalk.red(`当前key的可用剩余数不足！${file} 压缩失败！`))
          return
        }
        await imgMin(file)
      } else {
        // console.log(chalk.red(`不支持的文件格式 ${file}`));
      }
    }
  }
  async start(key) {
    try {
      const filePath = this.conf.imgMinPath
      //先判断key剩余的压缩数，或者认证
      const isValidated = await validate(filePath, key)
      if (!isValidated) {
        this.switchKey()
        return
      }

      await this.findImg(filePath)
    } catch (error) {
      console.log(error)
    }
    return Promise.resolve()
  }

  async switchKey() {
    const answers = await inquirer.prompt([
      {
        type: 'list',
        name: 'tinypngKey',
        message:
          '当前的apiKey已经用完额度或者Key已经失效，请切换一个apiKey使用',
        choices: [
          'MdcNxJs2pHBfs8BpMwrXc5qtxJghsxP2',
          'B6y2fnqqnyqffbnDvFRfPLN4fCbB5pR2',
          'nfQqXch720xCs2n8qrnBm9Yy4jmDgd4p',
        ],
      },
    ])
    this.conf.key = answers.tinypngKey
    this.start(this.conf.key)
  }
}

module.exports = ImgMin
